package com.example.monitor.service.impl;
import com.example.monitor.model.DTO.WorkshopTrendQueryDTO;
import com.example.monitor.model.VO.ResultVO;
import com.example.monitor.model.VO.WorkshopTrendVO;
import com.example.monitor.repository.AlarmRecordRepository;
import com.example.monitor.service.WorkshopTrendService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
public class WorkshopTrendServiceImpl implements WorkshopTrendService {

    private final AlarmRecordRepository alarmRecordRepository;

    @Override
    public ResultVO<WorkshopTrendVO> getWorkshopTrend(WorkshopTrendQueryDTO queryDTO) {
        // 解析时间范围
        Timestamp startTime = parseTimeRange(queryDTO.getTimeRange());

        // 获取日期列表
        List<String> dates = alarmRecordRepository.findDistinctDates(startTime);

        // 获取各车间每日数据
        List<Object[]> rawData = alarmRecordRepository.findDailyAlarmCount(
                queryDTO.getWorkshop(), startTime);

        // 处理数据为前端需要的格式
        WorkshopTrendVO result = processTrendData(dates, rawData);

        return ResultVO.success("查询成功", result);
    }

    private Timestamp parseTimeRange(String timeRange) {
        if (timeRange == null) {
            return Timestamp.valueOf(LocalDateTime.now().minusDays(7));
        }
        switch (timeRange) {
            case "1天": return Timestamp.valueOf(LocalDateTime.now().minusDays(1));
            case "1周": return Timestamp.valueOf(LocalDateTime.now().minusWeeks(1));
            case "1月": return Timestamp.valueOf(LocalDateTime.now().minusMonths(1));
            default: return Timestamp.valueOf(LocalDateTime.now().minusDays(7));
        }
    }

    private WorkshopTrendVO processTrendData(List<String> dates, List<Object[]> rawData) {
        // 按车间分组数据
        Map<String, Map<String, Integer>> workshopData = rawData.stream()
                .collect(Collectors.groupingBy(
                        arr -> (String) arr[0], // 车间名称
                        Collectors.toMap(
                                arr -> String.valueOf(arr[1]), // 日期
                                arr -> ((Number) arr[2]).intValue() // 数量
                        )
                ));

        // 构建系列数据
        List<WorkshopTrendVO.WorkshopTrendSeries> series = workshopData.entrySet().stream()
                .map(entry -> {
                    String workshop = entry.getKey();
                    Map<String, Integer> dailyCounts = entry.getValue();

                    // 为每个日期填充数据，没有数据的日期填0
                    List<Integer> data = dates.stream()
                            .map(date -> dailyCounts.getOrDefault(date, 0))
                            .collect(Collectors.toList());

                    return new WorkshopTrendVO.WorkshopTrendSeries(workshop, data);
                })
                .collect(Collectors.toList());

        // 构建返回对象
        WorkshopTrendVO result = new WorkshopTrendVO();
        result.setCategories(dates);
        result.setSeries(series);
        return result;
    }
}
